package com.wzt.lianfirecontrol.fragment;


import android.app.Dialog;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.MainActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.utils.BarFloorAdapter;
import com.wzt.lianfirecontrol.adapter.utils.FragmentPagerAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XksRecordModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaBuildingModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaPlanModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongBuildingModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongFloorModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.xiaokongshi.AddDutyDetailFragment;
import com.wzt.lianfirecontrol.fragment.xiaokongshi.DutyDetailFragment;
import com.wzt.lianfirecontrol.fragment.xuncha.xunchadevice.StartDeviceXunChaFragment;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.NoScrollViewPager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BarFloorFragment extends BaseFragment {
    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private RecyclerView rlv_title_bar;
    private LinearLayoutManager linearLayoutManager;
    private BarFloorAdapter barFloorAdapter;

    private View v_kuozhan_line;
    private ImageView iv_kuozhan;

    private NoScrollViewPager viewPager;
    private FragmentPagerAdapter fragmentPagerAdapter;
    private List<Fragment> fragments;
    private List<Fragment> webFragments;
    private int currentSelectPosition = -1;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private JianKongBuildingModel jianKongBuildingModel;
    private List<JianKongFloorModel> deviceFloorModels;

    private Dialog chooseFloorDialoag;

    private String barStyle = "0";// 导航显示 0楼层 1消控室详情 2预约维保 3报警复核单 4紧急维修单 5隐患整改 6巡检巡查 7防火巡查详情 8设备巡查详情
    private String bjPageType;

    private XksRecordModel xksRecordModel;

    private boolean isFirstLoad = true;
    private String ids;
    private String floorIds;
    private ArrayList<XunChaBuildingModel> buildModelList;
    private XunChaPlanModel xunChaPlanModel;

    private boolean isShowCad = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            if (null != bundle){
                barStyle = bundle.getString(ConstData.BARTYPE, "0");
                bjPageType = bundle.getString(ConstData.BJPAGETYPE, "0");
                ids = bundle.getString("ids", "");
                floorIds = bundle.getString("floorIds", "");
                buildModelList = (ArrayList<XunChaBuildingModel>) bundle.getSerializable("buildModelList");
                xunChaPlanModel = (XunChaPlanModel) bundle.getSerializable("xunChaPlanModel");
                if (bundle.containsKey("XksRecordModel")) {
                    xksRecordModel = (XksRecordModel) bundle.getSerializable("XksRecordModel");
                }
                jianKongBuildingModel = (JianKongBuildingModel) bundle.getSerializable("jianKongBuilding");
            }
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_bar_floor, container, false);
            initView();
            if ("0".equals(barStyle)) {
                if (null == jianKongBuildingModel
                        || null == jianKongBuildingModel.getChildren()
                        || jianKongBuildingModel.getChildren().size() == 0){
                    activity.finish();
                }
                deviceFloorModels = jianKongBuildingModel.getChildren();
                List<BannerModel> list = new ArrayList<>();
                for (JianKongFloorModel modle:deviceFloorModels) {
                    BannerModel bannerModel = new BannerModel();
                    bannerModel.setTitle(modle.getName());
                    list.add(bannerModel);
                }
                setFragments(list);
                ((ShowFragActivity)activity).setImageChangeAction(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isShowCad){
                            fragmentPagerAdapter.appendList(fragments);
                        }else {
                            fragmentPagerAdapter.appendList(webFragments);
                        }
                        viewPager.setAdapter(fragmentPagerAdapter);
                        viewPager.setCurrentItem(barFloorAdapter.getCurrrentPosition());
                        isShowCad = !isShowCad;
                        if (isShowCad) {
                            viewPager.setScroll(false);
                        }else {
                            viewPager.setScroll(true);
                        }
                    }
                });
            }
            List<String> alias = UserInfoModel.getUserInfo(activity).getRoleAlias();
            if ("2".equals(barStyle) && (alias.contains(RoleConstant.ROLE_REPAIR) || alias.contains(RoleConstant.ROLE_REPAIR_MANAGER))){
                MainActivity mainActivity = (MainActivity) activity;
                mainActivity.setRepairAction();
            }
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        initHeadView();
        initViewPager();

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        include_progress_bar.setVisibility(View.GONE);
        InitView.instance().initProgressBar(activity, include_progress_bar);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_data.setVisibility(View.GONE);

        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setVisibility(View.GONE);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });

        if (!"0".equals(barStyle)) {
            List<BannerModel> bannerModels = new ArrayList<>();
            switch (barStyle) {
                case "1":// 消控室值班
                    BannerModel bannerModel1 = new BannerModel();
                    bannerModel1.setTitle("值班检查");
                    bannerModels.add(bannerModel1);
                    BannerModel bannerModel2 = new BannerModel();
                    bannerModel2.setTitle("异常问题");
                    bannerModels.add(bannerModel2);
                    break;
                case "2":// 2预约维保
                    BannerModel bannerModel18 = new BannerModel();
                    bannerModel18.setTitle("待处理");
                    bannerModels.add(bannerModel18);
                    BannerModel bannerModel19 = new BannerModel();
                    bannerModel19.setTitle("维保中");
                    bannerModels.add(bannerModel19);
                    BannerModel bannerModel22 = new BannerModel();
                    bannerModel22.setTitle("待确认");
                    bannerModels.add(bannerModel22);
                    BannerModel bannerModel20 = new BannerModel();
                    bannerModel20.setTitle("已完成");
                    bannerModels.add(bannerModel20);
                    break;
                case "4":// 4紧急维修单
                    BannerModel bannerModel3 = new BannerModel();
                    bannerModel3.setTitle("待处理");
                    bannerModels.add(bannerModel3);
                    BannerModel bannerModel4 = new BannerModel();
                    bannerModel4.setTitle("已处理");
                    bannerModels.add(bannerModel4);
                    break;
                case "3":// 3报警复核单
                    BannerModel bannerModel5 = new BannerModel();
                    bannerModel5.setTitle("待复核");
                    bannerModels.add(bannerModel5);
                    BannerModel bannerModel6 = new BannerModel();
                    bannerModel6.setTitle("已复核");
                    bannerModels.add(bannerModel6);
                    break;
                case "5":// 隐患整改
                    BannerModel bannerModel7 = new BannerModel();
                    bannerModel7.setTitle("待整改");
                    bannerModels.add(bannerModel7);
                    BannerModel bannerModel21 = new BannerModel();
                    bannerModel21.setTitle("整改中");
                    bannerModels.add(bannerModel21);
                    BannerModel bannerModel8 = new BannerModel();
                    bannerModel8.setTitle("已整改");
                    bannerModels.add(bannerModel8);
                    break;
                case "6":// 巡检巡查
                    BannerModel bannerModel9 = new BannerModel();
                    bannerModel9.setTitle("防火巡查");
                    bannerModels.add(bannerModel9);
                    BannerModel bannerModel10 = new BannerModel();
                    bannerModel10.setTitle("防火检查");
                    bannerModels.add(bannerModel10);
                    BannerModel bannerModel11 = new BannerModel();
                    bannerModel11.setTitle("设备巡查");
                    bannerModels.add(bannerModel11);

                    if (activity instanceof ShowFragActivity) {
                        BannerModel editActionModel = new BannerModel();
                        editActionModel.setTitle("历史");
                        editActionModel.setActionType(ConstData.SHOWFRAG);
                        editActionModel.setActionValue(ConstData.XUNCHHISTORY);
                        editActionModel.setActionTitle("巡查历史");
                        Bundle bundle = new Bundle();
                        ((ShowFragActivity) activity).setTextEtAction(editActionModel, bundle);
                    }
                    break;
                case "7":// 7防火巡查详情
                    BannerModel bannerModel14 = new BannerModel();
                    bannerModel14.setTitle("检查项");
                    bannerModels.add(bannerModel14);
                    BannerModel bannerModel15 = new BannerModel();
                    bannerModel15.setTitle("问题");
                    bannerModels.add(bannerModel15);
                    break;
                case "8":// 8设备巡查详情
                    BannerModel bannerModel16 = new BannerModel();
                    bannerModel16.setTitle("设备");
                    bannerModels.add(bannerModel16);
                    BannerModel bannerModel17 = new BannerModel();
                    bannerModel17.setTitle("问题");
                    bannerModels.add(bannerModel17);
                    break;
            }


            setFragments(bannerModels);
        }
    }

    private void initHeadView() {
        rlv_title_bar = itemContentView.findViewById(R.id.rlv_title_bar);
        linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rlv_title_bar.setLayoutManager(linearLayoutManager);
        barFloorAdapter = new BarFloorAdapter(activity);
        rlv_title_bar.setAdapter(barFloorAdapter);
        barFloorAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<BannerModel>() {
            @Override
            public void onItemClick(View v, int position, BannerModel data) {
                viewPager.setCurrentItem(position);
            }
        });

        v_kuozhan_line = itemContentView.findViewById(R.id.v_kuozhan_line);
        iv_kuozhan = itemContentView.findViewById(R.id.iv_kuozhan);
    }

    private void initViewPager() {
        fragments = new ArrayList<>();
        webFragments = new ArrayList<>();
        viewPager = itemContentView.findViewById(R.id.viewPager);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setScroll(true);
        fragmentPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentSelectPosition = position;
                barFloorAdapter.setCurrrentPosition(position);
                if (position > 2) {
                    linearLayoutManager.scrollToPositionWithOffset(position - 2, 0);
                } else {
                    linearLayoutManager.scrollToPosition(0);
                }
                if (null != fragments){
                    Fragment fragment = fragments.get(position);
                    if (null != fragment && fragment instanceof BaseFragment && ((BaseFragment)fragment).isLoaded()) {
                        ((BaseFragment) fragment).updateData();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setFragments(final List<BannerModel> bannerModels) {
        if (null != bannerModels && bannerModels.size() > 0){
            include_no_data.setVisibility(View.GONE);
            currentSelectPosition = 0;
            if (bannerModels.size() > 6){
                v_kuozhan_line.setVisibility(View.GONE);
                iv_kuozhan.setVisibility(View.VISIBLE);
                iv_kuozhan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        chooseFloorDialoag = DialogUtils.getChooseListDialog(activity, bannerModels, "选择楼层",
                                currentSelectPosition, new BaseRecyclerAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View v, int position, Object data) {
                                        viewPager.setCurrentItem(position);
                                        DialogUtils.closeDialog(chooseFloorDialoag);
                                    }
                                });
                        chooseFloorDialoag.show();
                    }
                });
            }else {
                v_kuozhan_line.setVisibility(View.GONE);
                iv_kuozhan.setVisibility(View.GONE);
            }

            fragments.clear();
            barFloorAdapter.clear();
            for (int i = 0; i < bannerModels.size(); i++){
                BannerModel bannerModel = bannerModels.get(i);
                if (i == 0 && barStyle.equals("1")){// 消控室值班异常处理
                    if ("1".equals(xksRecordModel.getStatus())){// 1是记录
                        fragments.add(initAddJianchaFragment());
                    }else {
                        fragments.add(initJianchaFragment(bannerModel));
                    }
                }else if (i == 2 && barStyle.equals("6")){// 设备巡检
                    fragments.add(initDeviceXunJianFragment());
                }else {
                    fragments.add(initFragment(bannerModel, i));
                    if (barStyle == "0") {
                        viewPager.setScroll(false);
                        webFragments.add(initWebCadFragment(bannerModel, i));
                    }
                }
            }
            barFloorAdapter.addDatas(bannerModels);
            if (!isShowCad || !"0".equals(barStyle)) {
                fragmentPagerAdapter.appendList(fragments);
            }else {
                fragmentPagerAdapter.appendList(webFragments);
            }
            viewPager.setCurrentItem(0);
            barFloorAdapter.setCurrrentPosition(0);
        }else {
            include_no_data.setVisibility(View.VISIBLE);
        }
    }

    private Fragment initJianchaFragment(BannerModel bannerModel) {
        BaseFragment baseFragment = new DutyDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("XksRecordModel", xksRecordModel);
        HashMap<String, String> url_params = new HashMap<>();
        bundle.putString(ConstData.SHOWTYPPE, ConstData.UNUSUALLIST);
        bundle.putSerializable(ConstData.ACTIONPARAMS, url_params);
        bundle.putSerializable(ConstData.ACTIONMODLE, bannerModel);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    private Fragment initAddJianchaFragment() {
        BaseFragment baseFragment = new AddDutyDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("XksRecordModel", xksRecordModel);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    private Fragment initFragment(BannerModel bannerModel, int position) {
        BaseFragment baseFragment = new InfoListFragment();
        Bundle bundle = new Bundle();

        HashMap<String, String> url_params = new HashMap<>();
        switch (barStyle){
            case "0"://楼层
                bundle.putString(ConstData.SHOWTYPPE, ConstData.JIANKONGDEVICELIST);
                bundle.putSerializable("jianKongFloorModel", deviceFloorModels.get(position));
                break;
            case "1"://消控室值班
                if (1 == position){
                    bundle.putString(ConstData.SHOWTYPPE, ConstData.UNUSUALLIST);
                    bundle.putString("status", xksRecordModel.getStatus());
                    bundle.putSerializable("data", xksRecordModel);
                }
                break;
            case "2"://预约维保
                bundle.putString(ConstData.SHOWTYPPE, ConstData.YUYUE);
                if (0 == position){// 待处理
                    url_params.put("status", "1");
                }else if (1 == position){// 维保中
                    url_params.put("status", "2");
                }else if (2 == position){// 待确认
                    url_params.put("status", "3");
                }else {// 已完成
                    url_params.put("status", "4");
                }
                break;
            case "3"://报警复核
                bundle.putString(ConstData.BJPAGETYPE, bjPageType);
                bundle.putString(ConstData.SHOWTYPPE, ConstData.BAOJING);
                if (0 == position){
                    url_params.put("status", "0");
                }else {
                    url_params.put("status", "1");
                }
                switch (bjPageType){
                    case "0":// 监管
                        url_params.put("type", ConstData.JIANGUAN_STATUS);
                        break;
                    case "1":// 火警
                        url_params.put("type", ConstData.HUOJING_STATUS);
                        break;
                    case "2":// 预警
                        url_params.put("type", ConstData.YUJING_STATUS);
                        break;
                }
                break;
            case "4"://紧急维修单
                bundle.putString(ConstData.SHOWTYPPE, ConstData.JINGJI);
                if (0 == position){
                    url_params.put("status", "0");
                }else {
                    url_params.put("status", "1");
                }
                break;
            case "5"://隐患整改
                bundle.putString(ConstData.SHOWTYPPE, ConstData.YINGHUAN);
                if (0 == position){// 待整改
                    url_params.put("status", "0");
                }else if (1 == position){// 整改中
                    url_params.put("status", "1");
                }else {// 已整改
                    url_params.put("status", "2");
                }
                break;
            case "6"://巡检巡查
                bundle.putString(ConstData.SHOWTYPPE, ConstData.XUNCHA);
                switch (position){
                    case 0:// 防火巡查
                        bundle.putString("title", "防火巡查");
                        url_params.put("type", "1");
                        break;
                    case 1:// 防火检查
                        bundle.putString("title", "防火检查");
                        url_params.put("type", "2");
                        break;
                }
                break;
            case "7"://防火巡查详情
                bundle.putString("ids", ids);
                bundle.putString("floorIds", floorIds);
                bundle.putSerializable("buildModelList", buildModelList);
                bundle.putSerializable("xunChaPlanModel", xunChaPlanModel);
                if (0 == position){
                    bundle.putString(ConstData.SHOWTYPPE, ConstData.XUNCHAITEM);
                }else {
                    url_params.put("id", ids);
                    bundle.putString(ConstData.SHOWTYPPE, ConstData.XUNCHAQUESTION);
                }
                break;
            case "8"://设备巡查详情
                bundle.putSerializable("XunChaDeviceFloorModel", this.bundle.getSerializable("XunChaDeviceFloorModel"));
                if (0 == position){
                    bundle.putString(ConstData.SHOWTYPPE, ConstData.DEVICELIST);
                    bundle.putString(ConstData.ISDEVICECOMPLETE, this.bundle.getString(ConstData.ISDEVICECOMPLETE, "0"));
                }else {
                    bundle.putString(ConstData.SHOWTYPPE, ConstData.XUNCHADEVICEQUESTION);
                }
                break;
        }
        bundle.putSerializable(ConstData.ACTIONPARAMS, url_params);
        bundle.putSerializable(ConstData.ACTIONMODLE, bannerModel);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    private Fragment initWebCadFragment(BannerModel bannerModel, int position) {
        BaseFragment baseFragment = new WebCadFragment();
        HashMap<String, String> url_params = new HashMap<>();
        Bundle bundle = new Bundle();
        bundle.putSerializable("jianKongFloorModel", deviceFloorModels.get(position));
        bundle.putSerializable(ConstData.ACTIONPARAMS, url_params);
        bundle.putSerializable(ConstData.ACTIONMODLE, bannerModel);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    /**
     * 设备巡检
     * @return
     */
    private Fragment initDeviceXunJianFragment() {
        BaseFragment baseFragment = new StartDeviceXunChaFragment();
        Bundle bundle = new Bundle();
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    @Override
    public void imgSuccessAction(File file, String img, int photoWhat) {
        super.imgSuccessAction(file, img, photoWhat);
        if (null != fragments){
            if (currentSelectPosition >= 0 && fragments.size() > currentSelectPosition){
                ((BaseFragment)fragments.get(currentSelectPosition)).imgSuccessAction(file, img, photoWhat);
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(chooseFloorDialoag);
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            return;
        }
        switch (msg.what){

        }
    }

    @Override
    public void updateData() {
        super.updateData();
        if (barStyle == "0") {

        }else {
            if (null != fragments){
                for (Fragment fragment:fragments){
                    if (null != fragment && fragment instanceof BaseFragment && ((BaseFragment)fragment).isLoaded()) {
                        ((BaseFragment) fragment).updateData();
                    }
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstLoad){
            if ("0".equals(PreferencesUtils.getString(activity, ConstData.NEEDREFRESH, "1"))
                    || "2".equals(barStyle)
                    || "6".equals(barStyle)
                    || "8".equals(barStyle)) {
                PreferencesUtils.putString(activity, ConstData.NEEDREFRESH, "1");
                updateData();
            }
        }
        isFirstLoad = false;
    }
}
